package com.minxyz.seata;

import io.seata.common.util.StringUtils;
import io.seata.core.context.RootContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.support.HttpRequestWrapper;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.Iterator;

@Configuration
public class SeataRestTemplateAutoConfiguration {

    @Autowired(required = false)
    private Collection<RestTemplate> restTemplates;

    public SeataRestTemplateAutoConfiguration() {
    }

    @PostConstruct
    public void init() {
        if (this.restTemplates != null) {
            Iterator<RestTemplate> it = this.restTemplates.iterator();
            while (it.hasNext()) {
                it.next().getInterceptors().add((request, body, execution) -> {
                    HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);
                    String xid = RootContext.getXID();
                    if (StringUtils.isNotEmpty(xid)) {
                        requestWrapper.getHeaders().add(RootContext.KEY_XID, xid);
                    }
                    return execution.execute(requestWrapper, body);
                });
            }
        }

    }

}